import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Card, NavBar, IndexBar, List, Tag, SearchBar } from "antd-mobile";
import { EnvironmentOutline } from "antd-mobile-icons";
import { useDispatch } from "react-redux";
import { editChangeCity } from "../../store/CitySlice";
import http from "../../utils/http";
//import { debounce } from "lodash";
import useDebounce from "../../hooks/useDebounce";
import styles from "./index.module.css";

const Index = () => {
  const navigate = useNavigate();
  //获取路由参数，表示城市类型，例如：出发、目的地
  const { type } = useParams();
  const dispatch = useDispatch();

  const [cityList, setCityList] = useState([]);
  const [hotList, setHotList] = useState([]);
  const [SearchList, setSearchList] = useState([]);
  const [hisList, setHisList] = useState(
    JSON.parse(localStorage.getItem("hisList")) || []
  );

  const getCityList = async () => {
    const res = await http.get("/api/city");
    const { data } = res.data;
    setCityList(data.city);
    setHotList(data.hotCities);
  };

  useEffect(() => {
    getCityList();
  }, []);

  const handelGetCity = (city) => {
    dispatch(editChangeCity({ city, type }));
    navigate("/");
  };

  const handelSearch = useDebounce(async (value) => {
    if (value !== "") {
      const res = await http.get("/api/city/search", {
        params: { wd: value },
      });
      const { code, data } = res.data;
      if (code === 200) {
        setSearchList(data);
      }

      //历史记录
      const newHislist = [value, ...hisList];
      //去重
      const ind = newHislist.lastIndexOf(value);
      if (ind > 0) {
        newHislist.splice(ind, 1);
      }

      //将数据存储到本地
      localStorage.setItem("hisList", JSON.stringify(newHislist));

      setHisList(newHislist);
    } else {
      setSearchList([]);
    }
  }, 800);

  //清除历史记录
  const handelClear = () => {
    setHisList([]);
    localStorage.removeItem("hisList");
  };

  return (
    <div>
      <NavBar onBack={() => navigate("/")}>城市选择</NavBar>
      <SearchBar placeholder="请输入内容" onChange={handelSearch} />
      <div className={styles.search_wrap}>
        <List>
          {SearchList.length > 0 &&
            SearchList.map((item, index) => (
              <List.Item key={index}>{item.name}</List.Item>
            ))}
        </List>
      </div>

      <Card
        title={
          <h3 className={styles.hisTit}>
            历史搜索 <span onClick={() => handelClear()}>清除</span>
          </h3>
        }
      >
        <div className={styles.his_Wrap}>
          {hisList.map((item, index) => (
            <Tag key={index}>{item}</Tag>
          ))}
        </div>
      </Card>

      <Card
        title={
          <p className={styles.curpos}>
            热门城市:{" "}
            <EnvironmentOutline
              fontSize={20}
              color="skyblue"
              style={{ margin: "0px 5px" }}
            />
            {hotList.length > 0 && hotList[0].name}
          </p>
        }
      ></Card>
      <Card title="热门城市">
        <div className={styles.hot_wrap}>
          {hotList.length > 0 &&
            hotList.map((item, ind) => (
              <Tag onClick={() => handelGetCity(item.name)} key={ind}>
                {item.name}
              </Tag>
            ))}
        </div>
      </Card>
      <Card title="城市列表">
        <div style={{ height: window.innerHeight }}>
          <IndexBar>
            {cityList.length > 0 &&
              cityList.map((group) => {
                const { initial, list } = group;
                return (
                  <IndexBar.Panel
                    index={initial}
                    title={`${initial}`}
                    key={`${initial}`}
                  >
                    <List>
                      {list.map((item, index) => (
                        <List.Item
                          onClick={() => handelGetCity(item.name)}
                          key={index}
                        >
                          {item.name}
                        </List.Item>
                      ))}
                    </List>
                  </IndexBar.Panel>
                );
              })}
          </IndexBar>
        </div>
      </Card>
    </div>
  );
};

export default Index;
